/* eslint-disable no-unused-vars */
import { Article, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'

type Hometype = {
    userChannels:Channel[],
    active:string,
    allChannels:Channel[],
    channelArticles:{
      [key:number]:{
        timestamp:number,
        articles:Article[]
      }
    }
}
const initValue :Hometype = {
  userChannels: [],
  // 默认高亮
  active: '0',
  allChannels: [],
  channelArticles: {}
}

export default function home (state = initValue, action:HomeAction):Hometype {
  if (action.type === 'home/saveUserChannels') {
    return { ...state, userChannels: action.payload }
  } else if (action.type === 'home/changeActive') {
    return { ...state, active: action.payload }
  } else if (action.type === 'home/saveAllChannels') {
    return { ...state, allChannels: action.payload }
  } else if (action.type === 'home/saveChannelArticles') {
    // eslint-disable-next-line camelcase
    const { channel_id, timestamp, articles } = action.payload
    const old = state.channelArticles[channel_id]?.articles || []
    // console.log(oldObj, 444)
    // if (oldObj) {
    //   oldObj?.articles.push(...articles)
    //   // oldObj.articles.push
    //   oldObj.timestamp = timestamp
    //   const t = { ...state, [channel_id]: { ...oldObj } }
    //   console.log('t', t)
    //   return t
    // }
    return {
      ...state,
      channelArticles: {
        // 需要追加数据
        ...state.channelArticles,
        [channel_id]: {
          timestamp,
          articles: [...old, ...articles]
        }
      }
    }
  } else if (action.type === 'home/getNewArticles') {
    // 把文章加在已有的最前面
    // eslint-disable-next-line camelcase
    const { articles, channel_id, timestamp } = action.payload

    const oldArticles = state.channelArticles[channel_id].articles
    // console.log([...articles], 4455)

    const newArticles = [...articles, ...oldArticles]
    // const newArticles = [...articles]
    //
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp,
          articles: newArticles
        }
      }
    }
  }
  return state
}
